package com.qiku.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiku.reggie.dto.DishDto;
import com.qiku.reggie.mapper.CategoryMapper;
import com.qiku.reggie.mapper.DishMapper;
import com.qiku.reggie.pojo.Category;
import com.qiku.reggie.pojo.Dish;
import com.qiku.reggie.pojo.DishFlavor;
import com.qiku.reggie.service.CategoryService;
import com.qiku.reggie.service.DishFlavorService;
import com.qiku.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public void saveWithDishFlavor(DishDto dishDto) {
        // 1 保存菜品  dish
        this.save(dishDto);
        // 2 保存口味  dish_flavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {

        // 1 查询菜品dish表 select * from dish where  id = ?
        Dish dish = this.getById(id);

        // 2 查询口味数据 select * from dish_flavor where dish_id = ?
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id" , id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

        // 3 合并dish + dishFlavorList = dishDto
        DishDto dishDto = new DishDto(); // DishDto = Dish + List<DishFlavor>
        BeanUtils.copyProperties(dish , dishDto);
        dishDto.setFlavors(dishFlavorList);

        return dishDto;
    }


    @Override
    @Transactional
    public void updateByIdWithFlavo(DishDto dishDto) {
        // 先更新菜品数据  update dish set ... = ... where id = ?
        this.updateById(dishDto);
        // 清空菜品对应的所有口味数据 delete from dish_flavor where dish_id = ?
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id" , dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        // 添加提交的所有口味数据
        List<DishFlavor> dishFlavorsList = dishDto.getFlavors();
        // 给每个菜品口味设置dishId
        dishFlavorsList.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishFlavorsList);
    }

}
